# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.serviceDao import ServiceDao

import time
from . import app

localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
CORS(app, supports_credentials=True)


@app.route('/queryServiceById', methods=['POST'])
def queryServiceById():
    if not request.json:
        abort(400)
    id = request.json.get("id")
    try:
        total_count, userCodeJSON = ServiceDao().queryServiceById(id)
        if total_count:
            return jsonify({"message": {"code": 1, "status": "queryService OK"}, "info": userCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 1, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/queryServiceByCondition', methods=['POST'])
def queryServiceByCondition():
    if not request.json:
        abort(400)
    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})
    try:
        conditions = request.json['condition']
        # field = conditions['field']
        # op = conditions['op']
        # value = conditions['value']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
        # sortField = multiSort['field']
        # sort = multiSort['sort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})
    try:
        total_count, UserCodeJSON = ServiceDao().queryServiceByCondition(pageIndex=pageIndex, pageSize=pageSize,conditions=conditions, multiSort=multiSort)

        if total_count:
            return jsonify({"message": {"code": 1, "status": "querService OK"}, "total": total_count, "info": UserCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 1, "status": "No  data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/insertService', methods=['POST'])
def insertService():
    if not request.json:
        abort(400)

    Info = {

        'serviceName': request.json.get('serviceName'),  #
        'serviceCode': request.json.get('serviceCode'),  #
        'servicePrice': request.json.get('servicePrice'),  #
        'serviceRate': request.json.get('serviceRate'),  #
        'serviceStatus': request.json.get('serviceStatus'),
        'serviceContent': request.json.get('serviceContent'),
        'serviceContact': request.json.get('serviceContact'),
        'serviceStartDate': request.json.get('serviceStartDate'),
        'serviceEndDate': request.json.get('serviceEndDate')

    }
    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
    try:
        tc, rs = ServiceDao().insertService(Info)
        if tc:
            return jsonify(
                {"massage": {"code": 1}, "info": rs})  # 添加函数调用成功，返回添加的信息（不包括userRecharge的Id）
        else:
            return jsonify({"message": {"code": 0, "info": "addService Error"}})  # 添加函数调用失败
    except Exception, e:
        return jsonify({"message": {"code": 0, "info": str(e)}})





@app.route('/insertServiceByItem', methods=['POST'])
def insertServiceByItem():
    if not request.json:
        abort(400)

    Info = {

        'serviceName': request.json.get('serviceName'),  #
        'serviceCode': request.json.get('serviceCode'),  #
        'servicePrice': request.json.get('servicePrice'),  #
        'serviceRate': request.json.get('serviceRate'),  #
        'serviceStatus': request.json.get('serviceStatus'),
        'serviceContent': request.json.get('serviceContent'),
        'serviceContact': request.json.get('serviceContact'),
        'serviceStartDate': request.json.get('serviceStartDate'),
        'serviceEndDate': request.json.get('serviceEndDate'),
        "itemId": request.json.get('itemId')

    }
    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
    try:
        tc, rs = ServiceDao().insertServiceByItem(Info)
        # except:
        #     return jsonify({"message": {"code": 0, "info": "信息填写错误"}})
        if tc:
            return jsonify(
                {"massage": {"code": 1}, "info": rs})  # 添加函数调用成功，返回添加的信息（不包括userRecharge的Id）
        else:
            return jsonify({"message": {"code": 0, "info": "addService Error"}})  # 添加函数调用失败

    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


@app.route('/updateService', methods=['POST'])
def updateService():  #
    try:
        id = request.json['id']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 id"}})
    try:
        oldInfo = ServiceDao().selectService(id)
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
    Info = {
        'id': request.json.get('id'),  #
        'serviceName': request.json.get('serviceName', oldInfo[1]),  #
        'serviceCode': request.json.get('serviceCode', oldInfo[2]),  #
        'servicePrice': request.json.get('servicePrice', oldInfo[3]),  #
        'serviceRate': request.json.get('serviceRate', oldInfo[4]),  #
        'serviceStatus': request.json.get('serviceStatus', oldInfo[5]),
        'serviceContent': request.json.get('serviceContent', oldInfo[6]),
        'serviceContact': request.json.get('serviceContact', oldInfo[7]),
        'serviceStartDate': request.json.get('serviceStartDate', oldInfo[8]),
        'serviceEndDate': request.json.get('serviceEndDate', oldInfo[9])

    }
    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
    try:
        rs = ServiceDao().updateService(Info)
        if rs:
            return jsonify(
                {"info": Info, "massage": {"code": 1, "info": "updateService OK"}})  # 添加函数调用成功，返回添加的信息
        else:
            return jsonify({"message": {"code": 0, "info": "updateService Error"}})  # 添加函数调用失败
    except Exception, e:
        return jsonify({"message": {"code": 0, "info": str(e)}})



@app.route('/deleteService', methods=['POST'])  # 根据id数组删除zzh_user_Code表指定记录,传入格式为 "ids":[1,2,3,4]
def deleteService():
    ids = request.json.get("ids")
    if not ids:
        return jsonify({"message": "请输入待删除的  id数组！"})
    try:
        rs = ServiceDao().deleteService(ids)
        if rs:
            return jsonify({"message": {"code": 1, "info": "deleteService OK"}})
        else:
            return jsonify({"message": {"code": 0, "info": "deleteService  Error"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})
